package com.ydkj.a37e_mall.Classes.Fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.TextView;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshExpandableListView;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.LoginActivity;
import com.ydkj.a37e_mall.Classes.Applicatiom.MyApplication;
import com.ydkj.a37e_mall.Classes.Model.Request.GetALLDistributionReq;
import com.ydkj.a37e_mall.Classes.Model.Response.GetALLDistributionResp;
import com.ydkj.a37e_mall.R;
import com.ydkj.a37e_mall.Resource.Utils.Async_http_get;
import com.ydkj.a37e_mall.Resource.Utils.CommonUtil;
import com.ydkj.a37e_mall.Resource.Utils.Const;
import com.ydkj.a37e_mall.Resource.Utils.GsonImpl;
import com.ydkj.a37e_mall.Resource.Utils.SharedPreferencesUtil;
import com.ydkj.a37e_mall.Resource.View.CustomProgressDialog;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import cz.msebera.android.httpclient.Header;

import static com.ydkj.a37e_mall.Classes.Acitivity.BaseActivity.BaseActivity.page;

/**
 * Created by Administrator on 2017/1/13.
 * <p>
 * 配送订单   完成
 */

public class CompDistributionOrderFg extends BaseFg {
    private View rootView;
    private Activity mActivity;
    private SharedPreferencesUtil sharedPreferencesUtil;
    private MyApplication myApplication;
    private PullToRefreshExpandableListView ref_ealv_comp_distributionorder;
    private CompDistributionOrderAdapter compDistributionOrderAdapter;
    private List<GetALLDistributionResp.ResultEntity.DataEntity> grouplist;
    private List<List<GetALLDistributionResp.ResultEntity.DataEntity>> childlist;
    public static final int LOAD = 0;// 加载
    public static final int REFRESH = 1;// 刷新
    public static final int MORE = 2;// 更多

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.comp_distributionorder, container, false);
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }

        return rootView;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        mActivity = getActivity();
        init();


    }

    private void init() {
        sharedPreferencesUtil = SharedPreferencesUtil.getInstance(mActivity);
        myApplication = MyApplication.getInstance();
        ref_ealv_comp_distributionorder = (PullToRefreshExpandableListView) mActivity.findViewById(R.id.ref_ealv_comp_distributionorder);
        ref_ealv_comp_distributionorder.getRefreshableView().setGroupIndicator(null);
        ref_ealv_comp_distributionorder.getRefreshableView().setDivider(null);

        grouplist = new ArrayList<>();
        childlist = new ArrayList<>();
        GetALLDistributionOrderList(REFRESH);
        compDistributionOrderAdapter = new CompDistributionOrderAdapter(grouplist, childlist);
        ref_ealv_comp_distributionorder.getRefreshableView().setAdapter(compDistributionOrderAdapter); //PullToRefreshExpandableListView 设置BaseExpandableListAdapter 适配器方法


        ref_ealv_comp_distributionorder.setOnRefreshListener2(new PullToRefreshBase.OnRefreshListener2<ExpandableListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ExpandableListView> refreshView) {
                GetALLDistributionOrderList(REFRESH);
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ExpandableListView> refreshView) {
                GetALLDistributionOrderList(MORE);
            }
        });
    }

    private void GetALLDistributionOrderList(final int type) {
        if (myApplication.getDataEntity().getStore_id().size() == 0) {
            return;
        }
        CustomProgressDialog.createDialog(mActivity).Show();
        GetALLDistributionReq req = new GetALLDistributionReq();
        if (type == LOAD || type == REFRESH) {
            page = 1;
        } else {
            page = grouplist.size() / 10 + 1;
        }
        req.setUuid(myApplication.getDataEntity().getUuid());
        req.setStore_id(myApplication.getDataEntity().getStore_id().get(0) + "");
        req.setDelivery_type("3");
        req.setStats("6");
        req.setPage(page + "");
        req.setPage_size("10");


        RequestParams params = new RequestParams();
        params.put("token", sharedPreferencesUtil.getAccessToken());
        params.put("secret", req.getSecret());
        Async_http_get.get(Const.COMMON_ADDRESS + req.urlString(), params, new JsonHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                CustomProgressDialog.Dismiss();
                Log.e("url", "all_mall_order_json==" + response);
                String errno = response.optString("errno");
                String errmsg = response.optString("errmsg");
                if (errmsg.equals("暂无订单")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    grouplist.clear();
                    childlist.clear();
                    ref_ealv_comp_distributionorder.onRefreshComplete();
                    compDistributionOrderAdapter.notifyDataSetChanged();

                    return;
                }
                if (errno.equals("000")) {

                    GetALLDistributionResp resp = GsonImpl.get().toObject(response.toString(), GetALLDistributionResp.class);
                    if (type == LOAD || type == REFRESH) {
                        grouplist.clear();
                        grouplist.addAll(resp.getResult().getData());
                        for (int i = 0; i < grouplist.size(); i++) {
                            List<GetALLDistributionResp.ResultEntity.DataEntity> list = new ArrayList<GetALLDistributionResp.ResultEntity.DataEntity>();
                            list.add(grouplist.get(i));
                            childlist.add(list);

                        }
                    } else {
                        grouplist.addAll(resp.getResult().getData());
                        for (int i = 0; i < grouplist.size(); i++) {
                            List<GetALLDistributionResp.ResultEntity.DataEntity> list = new ArrayList<GetALLDistributionResp.ResultEntity.DataEntity>();
                            childlist.add(list);
                        }
                    }
                    if (grouplist.size() % 10 > 0) {
                        ref_ealv_comp_distributionorder.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                        Log.e("url", "123123");
                    } else {
                        ref_ealv_comp_distributionorder.setMode(PullToRefreshBase.Mode.BOTH);
                    }
                    ref_ealv_comp_distributionorder.onRefreshComplete();
                    compDistributionOrderAdapter.notifyDataSetChanged();
                } else if (errno.equals("999")) {
                    CommonUtil.showToast(mActivity, errmsg);
                    Intent intent = new Intent(mActivity, LoginActivity.class);
                    startActivityForResult(intent, 3);
                    Log.e("url", "errmsg==" + errmsg);
                    ref_ealv_comp_distributionorder.onRefreshComplete();
                } else if (errno.equals("008")) {
//                    CommonUtil.showToast(mActivity, errmsg);
                    grouplist.clear();
                    ref_ealv_comp_distributionorder.onRefreshComplete();
                    compDistributionOrderAdapter.notifyDataSetChanged();
                } else if (errno.equals("0")) {
                    ref_ealv_comp_distributionorder.onRefreshComplete();
                    Log.e("url", "errmsg==" + errmsg);
                    CommonUtil.showToast(mActivity, "数据加载完了");
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                CustomProgressDialog.Dismiss();
                CommonUtil.showToast(mActivity, "网络连接失败");
            }
        });
    }

    private class CompDistributionOrderAdapter extends BaseExpandableListAdapter {
        private List<GetALLDistributionResp.ResultEntity.DataEntity> group;
        private List<List<GetALLDistributionResp.ResultEntity.DataEntity>> child;


        public CompDistributionOrderAdapter(List<GetALLDistributionResp.ResultEntity.DataEntity> group, List<List<GetALLDistributionResp.ResultEntity.DataEntity>> child) {

            this.group = group;
            this.child = child;
        }

        @Override
        public int getGroupCount() {
            return group.size();
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            return child.get(groupPosition).size();
        }

        @Override
        public GetALLDistributionResp.ResultEntity.DataEntity getGroup(int groupPosition) {
            return group.get(groupPosition);
        }

        @Override
        public GetALLDistributionResp.ResultEntity.DataEntity getChild(int groupPosition, int childPosition) {
            return child.get(childPosition).get(childPosition);
        }

        @Override
        public long getGroupId(int groupPosition) {
            return groupPosition;
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            return childPosition;
        }


        /**
         * 显示：group
         */
        @Override
        public View getGroupView(final int groupPosition, boolean isExpanded,
                                 View convertView, ViewGroup parent) {
            ViewHolder vh;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(
                        R.layout.distributionorder_group_list, null);
                vh = new ViewHolder();

                vh.img_group = (ImageView) convertView.findViewById(R.id.img_group);
                vh.tv_group_order_num = (TextView) convertView.findViewById(R.id.tv_group_order_num);
                vh.tv_group_order_state = (TextView) convertView.findViewById(R.id.tv_group_order_state);
                vh.tv_group_order_type = (TextView) convertView.findViewById(R.id.tv_group_order_type);
                vh.tv_group_immediate_distribution = (TextView) convertView.findViewById(R.id.tv_group_immediate_distribution);
                vh.tv_group_order_abnormal = (TextView) convertView.findViewById(R.id.tv_group_order_abnormal);

            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);
            vh.tv_group_order_num.setText(group.get(groupPosition).getSn());
            vh.tv_group_immediate_distribution.setVisibility(View.GONE);
            vh.tv_group_order_abnormal.setVisibility(View.GONE);
            vh.tv_group_order_state.setVisibility(View.GONE);
            vh.tv_group_order_type.setText("已完成");
            //箭头的切换
            if (isExpanded) {
                vh.img_group.setImageResource(R.mipmap.array_up2);
            } else {
                vh.img_group.setImageResource(R.mipmap.array_down2);
            }
            return convertView;

        }

        /**
         * 显示：child
         */
        @Override
        public View getChildView(int groupPosition, int childPosition,
                                 boolean isLastChild, View convertView, ViewGroup parent) {
            ViewHolder vh;
            if (convertView == null) {
                convertView = LayoutInflater.from(mActivity).inflate(
                        R.layout.distributionorder_child_list, null);
                vh = new ViewHolder();
                vh.tv_child_contact_name = (TextView) convertView.findViewById(R.id.tv_child_contact_name);
                vh.tv_child_contact_num = (TextView) convertView.findViewById(R.id.tv_child_contact_num);
                vh.tv_child_profit_balance = (TextView) convertView.findViewById(R.id.tv_child_profit_balance);
                vh.tv_child_distribution_adress = (TextView) convertView.findViewById(R.id.tv_child_distribution_adress);
                vh.tv_child_money_content = (TextView) convertView.findViewById(R.id.tv_child_money_content);

            } else {
                vh = (ViewHolder) convertView.getTag();
            }
            convertView.setTag(vh);
            vh.tv_child_contact_name.setText(getChild(groupPosition, childPosition).getConsignee());
            vh.tv_child_contact_num.setText(getChild(groupPosition, childPosition).getMobile());
            vh.tv_child_profit_balance.setText(getChild(groupPosition, childPosition).getTotal_fee());
            vh.tv_child_distribution_adress.setText(getChild(groupPosition, childPosition).getAddress());
            vh.tv_child_money_content.setText(getChild(groupPosition, childPosition).getInfo());
            return convertView;
        }

        class ViewHolder {
            TextView tv_group_order_num, tv_group_order_state, tv_group_immediate_distribution, tv_group_order_abnormal, tv_group_order_type;
            TextView tv_child_contact_name, tv_child_contact_num, tv_child_profit_balance, tv_child_distribution_adress, tv_child_money_content;
            ImageView img_group;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return false;
        }

        @Override
        public boolean hasStableIds() {
            return false;
        }

    }

}
